<template>
  <div ref="lineDemo" :id="id" class="myEcharts"></div>
</template>

<script>
//引入echarts
import * as echarts from 'echarts';

export default {
  name: 'Bar1',
  props: ['id'], // 父组件传入的id
  data() {
    return {
      myChart: null,
      chartData: null
    };
  },
  methods: {
    // 打开echer 等待
    ecLoading() {
      this.myChart.showLoading({
        text: '',
        color: '#000',
        maskColor: 'rgba(255, 255, 255, 0)',
        showSpinner: true,
        spinnerRadius: 16,
        lineWidth: 3
      });
    },

    noData() {
      this.myChart.clear(); // 清除图表内容
      this.myChart.showLoading({
        text: '暂无数据',
        showSpinner: false, // 隐藏加载中的转圈动图
        textColor: '#000',
        maskColor: 'rgba(255, 255, 255, 0)',
        fontSize: '25px',
        fontWeight: 'bold',
        fontFamily: 'Microsoft YaHei'
      });
    },

    // 从父组件接收数据并更新图表
    setOption(data) {
      if (!data || Object.keys(data).length === 0) {
        this.noData();
        return;
      }
      
      this.chartData = data;
      this.echartInit();
    },

    // echarts标准格式
    echartInit() {
      // 文字大小适配
      const fontSize = (res) => {
        const clientWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
        if (!clientWidth) return;
        let fontSize = clientWidth / 1920;
        return res * fontSize;
      };

      // 只使用传入的数据，不使用默认数据
      if (!this.chartData || Object.keys(this.chartData).length === 0) {
        this.noData();
        return;
      }

      let data = this.chartData;
      
      let colors = [
        '#4C98FB',
        '#83CCE7',
        '#26C7C8',
        '#73DEBD',
        '#26C978',
        '#8CDF6C',
        '#FBD657',
        '#F56679',
        '#E07BCE',
        '#9D50E0',
        '#634FDA'
      ];
      
      let processedData = {
        area: [],
        legend: [],
        data: []
      };
      
      // 提取日期作为area
      processedData.area = Object.keys(data);
      
      // 提取所有的类别（未归、早出等）作为legend
      const firstDate = Object.keys(data)[0];
      processedData.legend = Object.keys(data[firstDate]).filter(key => key !== 'total');
      
      // 为每个类别准备数据
      processedData.legend.forEach(category => {
        const categoryData = [];
        processedData.area.forEach(date => {
          categoryData.push(data[date][category]);
        });
        processedData.data.push(categoryData);
      });
      // 创建series数组
      let series = [];
      processedData.legend.forEach((name, index) => {
        series.push({
          name: name,
          type: 'bar',
          stack: 'total',
          emphasis: {
            focus: 'series',
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          },
          data: processedData.data[index]
        });
      });
      
      let option = {
        // title: {
        //   text: '通行情况',
        //   left: 19,
        //   top: 15,
        //   textStyle: {
        //     color: '#000'
        //   }
        // },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          backgroundColor: 'rgba(0, 0, 0, 0.7)',
          borderColor: '#4C98FB',
          textStyle: {
            color: '#fff'
          },
          formatter: function(params) {
            let result = params[0].name + '<br/>';
            // 从原始数据中获取对应日期的total值
            let total = data[params[0].name] ? data[params[0].name].total : 0;
            params.forEach(item => {
              result += item.marker + item.seriesName + ': ' + item.value + '<br/>';
            });
            result += '应归人数: ' + total;
            return result;
          }
        },
        color: colors,
        legend: {
          top: 10,
          left: 200,
          itemWidth: 10,
          itemHeight: 10,
          // padding: [5, 10],
          textStyle: {
            fontSize: 14,
            color: '#96A4F4',
            padding: [3, 0, 0, 0]
          },
          data: processedData.legend
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '5%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          axisLabel: {
            color: '#96A4F4'
          },
          axisLine: {
            lineStyle: {
              color: '#96A4F4'
            },
            width: 5
          },
          axisTick: {
            show: false
          },
          data: processedData.area
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            color: '#96A4F4'
          },
          axisLine: {
            lineStyle: {
              color: '#96A4F4'
            },
            width: 5
          },
          axisTick: {
            show: false
          },
          splitLine: {
            lineStyle: {
              color: 'rgba(150, 164, 244, 0.3)'
            }
          }
        },
        series: series // 使用创建的series数组
      };

      // 设置图表选项
      this.myChart.hideLoading();
      this.myChart.setOption(option);
    },

    handleResize() {
      if (this.myChart) {
        this.myChart.resize();
      }
    }
  },
  mounted() {
    // 获取DOM元素并初始化
    this.myChart = echarts.init(document.getElementById(this.id));
    // 立即调用echartInit方法显示图表
    this.ecLoading();
    // 使用setTimeout确保DOM已经完全渲染
    // setTimeout(() => {
    //   this.echartInit();
    // }, 100);
    window.addEventListener('resize', this.handleResize);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
    if (this.myChart) {
      this.myChart.dispose();
    }
  }
};
</script>
<style scoped>
.myEcharts {
  width: 100%;
  height: 100%;
}
</style>
